package com.primal.util;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author whh
 * Date 2023/10/11/ 19:59
 * <p></p>
 */
public class AsyncManager {

    //延时执行时间
    private long delay = 10;

    private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10,new DefaultThreadFactory());

    private static final AsyncManager me = new AsyncManager();


    private AsyncManager(){}

    public static AsyncManager me(){
        return me;
    }


    /**
     * 提交任务
     * @param task
     */
    public void submit(Runnable task){
        this.executor.schedule(task,delay, TimeUnit.SECONDS);
    }


    /**
     * 设置任务延时执行时间 单位秒
     * @param delay
     * @return
     */
    public AsyncManager setDelay(long delay) {
        this.delay = delay;
        return this;
    }

    /**
     * 停止线程池
     */
    public void shutdown(){
        this.executor.shutdown();
    }


    /**
     * 线程池工厂
     */
    private static class DefaultThreadFactory implements ThreadFactory{
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

}
